package org.greyhawk.samonitor.service;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.greyhawk.samonitor.domain.Resources;
import org.greyhawk.samonitor.domain.ResourcesType;
import org.springframework.stereotype.Service;

@Service
public class FileGenerater {
	
	private final String ROOT_PATH = "D:\\upload\\";
	
	//private final String ROOT_PATH = "/home/wutq/tmp/upload/";
	
	
	
	public void generateFile(Resources resources) throws Exception{
		String dirPath = this.createPath(resources.getSite().getName(), resources.getType());
		this.mkdir(dirPath);
		String fileName = resources.getName();
		File file = new File(dirPath.concat(fileName));
		InputStream inputStream = new ByteArrayInputStream(resources.getData());
		this.writeToFile(inputStream, file);
	}
	
	
	public byte[] readResources(Resources resources)throws Exception{
		String dirPath = this.createPath(resources.getSite().getName(), resources.getType());
		String fileName = resources.getName();
		File file = new File(dirPath.concat(fileName));
		return readToFile(file);
	}

	public void mkdir(String dirPath) {
		File dir = new File(dirPath);
		if (!dir.exists())
			dir.mkdirs();
	}
	
	public String createPath(String siteName,ResourcesType resourcesType){
		StringBuffer buffer = new StringBuffer();
		buffer.append(ROOT_PATH);
		buffer.append(siteName);
		buffer.append(File.separator);
		buffer.append(resourcesType.getDesc());
		buffer.append(File.separator);
		return buffer.toString();
	}


	public void writeToFile(InputStream inputStream, File file)
			throws Exception {
		System.out.println("========write to:"+file.getPath());
		DataOutputStream out = new DataOutputStream(new BufferedOutputStream(
				new FileOutputStream(file)));
		int c;
		while ((c = inputStream.read()) != -1) {
			out.write(c);
		}
		inputStream.close();
		out.close();
	}
	
	public byte[] readToFile(File file)throws Exception{
		InputStream is = new FileInputStream(file);
		byte[] bytes = new byte[(int)file.length()];
		int offset = 0; 
		int numRead = 0; 
		while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { 
			offset += numRead; 
			} 
		return bytes;
	}

}
